package com.sctvcloud.zhaohua_sd.ui.dialog;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;

import com.jiongbull.jlog.JLog;
import com.mob.MobSDK;
import com.ruihang.generalibrary.beans.ShareItem;
import com.ruihang.generalibrary.ui.adapter.ShareGrideAdapter;
import com.ruihang.generalibrary.ui.dialog.BaseBottomSheetFrag;
import com.ruihang.generalibrary.ui.dialog.ShareFragment;
import com.ruihang.generalibrary.ui.dialog.SystemShareDialogFragment;
import com.ruihang.generalibrary.ui.util.FragmentDialogShowHelper;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.IShares;
import com.sctvcloud.zhaohua_sd.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.system.email.Email;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * 分享APP以及邀请码弹窗
 */
public class ShareFragmentView extends BaseBottomSheetFrag implements AdapterView.OnItemClickListener
        , PlatformActionListener {

    //    private IShares shares;
    private String invitation;//邀请码
    private String title;//邀请码
    private String downloadAppAddress;//分享的APP的下载地址
    private GridView shareList;
    private CustomFontTextView titleView;
    private CustomFontTextView invitaionView;
    private ShareSuccess shareListener;

    private ShareGrideAdapter shareAdapter;
    private SystemShareDialogFragment mDialogFragment;
    protected FragmentDialogShowHelper fragmentDialogShowHelper;

    private static final int WHAT_ERROR = 1;
    private static final int WHAT_CANCLE = 2;
    private static final int WHAT_SUC = 3;
    private Pair<String, String> pairs;
    private OnShareAppClickListener onShareAppClickListener;
    public ShareFragmentView( ){
    }

    @SuppressLint("ValidFragment")
    public ShareFragmentView(String invitation,ShareSuccess li){
        this.invitation = invitation;
        this.shareListener = li;
    }

    public interface OnShareAppClickListener {
        void onClick(Pair<String, String> pairs);
    }

    public void setOnShareAppClickListener(OnShareAppClickListener onShareAppClickListener) {
        this.onShareAppClickListener = onShareAppClickListener;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public int getLayoutResId() {
        return R.layout.dia_share_fragment_view;
    }

    public void initView() {
        shareList = (GridView) rootView.findViewById(R.id.share_list);
        titleView = (CustomFontTextView) rootView.findViewById(R.id.title);
        titleView.setText("快分享给小伙伴");
        invitaionView = (CustomFontTextView) rootView.findViewById(R.id.invitation);
        if(!TextUtils.isEmpty(invitation)){
            invitaionView.setText(invitation);
        }
        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        ViewGroup.LayoutParams lp = shareList.getLayoutParams();
        lp.width = width;
        List<ShareItem> list = new ArrayList<>();
        list.add(new ShareItem(com.ruihang.generalibrary.R.drawable.icon_share_wx, com.ruihang.generalibrary.R.string.share_weixin).setTag(Wechat.NAME));
        list.add(new ShareItem(com.ruihang.generalibrary.R.drawable.icon_share_wfcircle, com.ruihang.generalibrary.R.string.share_pyq).setTag(WechatMoments.NAME));
        list.add(new ShareItem(com.ruihang.generalibrary.R.drawable.icon_share_qq, com.ruihang.generalibrary.R.string.share_qq).setTag(QQ.NAME));
        list.add(new ShareItem(com.ruihang.generalibrary.R.drawable.icon_share_qspace, com.ruihang.generalibrary.R.string.share_qq_space).setTag(QZone.NAME));
        list.add(new ShareItem(com.ruihang.generalibrary.R.drawable.icon_share_wb, com.ruihang.generalibrary.R.string.share_sina).setTag(SinaWeibo.NAME));
        list.add(new ShareItem(com.ruihang.generalibrary.R.drawable.icon_share_email, com.ruihang.generalibrary.R.string.share_eamil).setTag(Email.NAME));
//        list.add(new ShareItem(com.ruihang.generalibrary.R.drawable.icon_share_system, com.ruihang.generalibrary.R.string.share_system).setTag("System"));
//        list.add(new ShareItem(R.drawable.share_tencent,R.string.share_tencent).setTag(TencentWeibo.NAME));
        shareAdapter = new ShareGrideAdapter(getContext(), list);
        shareList.setAdapter(shareAdapter);
        shareList.setOnItemClickListener(this);

    }

//    public IShares getShares() {
//        return shares;
//    }
//
//    public void setShares(IShares shares) {
//        this.shares = shares;
//    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getInvitation() {
        return invitation;
    }

    public void setInvitation(String invitation) {
        this.invitation = invitation;
    }

    public String getDownloadAppAddress() {
        return downloadAppAddress;
    }

    public void setDownloadAppAddress(String downloadAppAddress) {
        this.downloadAppAddress = downloadAppAddress;
    }

    private void setSharePlatform(Platform form) {
        form.setPlatformActionListener(this);

    }

    private Platform.ShareParams getShareParams(String name) {
//        JLog.e("ishare=" + ishares);
        Platform.ShareParams sp = null;
        boolean setUrl = true;
        boolean isWebPage = true;
        boolean isQQ = false;
        if (QQ.NAME.equals(name)) {
            sp = new QQ.ShareParams();
            isQQ = true;
            pairs = new Pair<>("行为类型", "分享到QQ好友");
        } else if (QZone.NAME.equals(name)) {
            sp = new QZone.ShareParams();
            pairs = new Pair<>("行为类型", "分享到QQ空间");
        } else if (Wechat.NAME.equals(name)) {
            sp = new Wechat.ShareParams();
            pairs = new Pair<>("行为类型", "分享到微信好友");
        } else if (WechatMoments.NAME.equals(name)) {
            sp = new WechatMoments.ShareParams();
            pairs = new Pair<>("行为类型", "分享到朋友圈");
        } else if (SinaWeibo.NAME.equals(name)) {
            sp = new SinaWeibo.ShareParams();
            setUrl = false;
            isWebPage = false;
            pairs = new Pair<>("行为类型", "分享到微博");
        } else if (Email.NAME.equals(name)) {
            sp = new Email.ShareParams();
            pairs = new Pair<>("行为类型", "分享到电子邮箱");
        }

        if (sp != null) {
//            sp.setTitle(ishares.getShareTitle());
//            sp.setTitleUrl(ishares.getShareURL());
            sp.setTitle(this.getString(com.ruihang.generalibrary.R.string.app_name)+"APP---点击下载");
            sp.setTitleUrl(downloadAppAddress);
            if (setUrl) {
                sp.setUrl(downloadAppAddress);
            }
            sp.setShareType(Platform.SHARE_WEBPAGE);
            sp.setImageUrl("http://file.zhgbtv.cn/sctv/logo/sd_logo.png");
            sp.setTitleUrl(downloadAppAddress);
            sp.setSiteUrl("http://www.sctv.cn");
            sp.setSite(this.getString(com.ruihang.generalibrary.R.string.app_name));
            sp.setText("蜀道昭化 可视天下"+"\n邀请码：" + invitation);
            if (SinaWeibo.NAME.equals(name)) {
                sp.setText(this.getString(com.ruihang.generalibrary.R.string.app_name)+"APP---点击下载  " + downloadAppAddress);
                if (!isValidClientSina("com.sina.weibo")) {
                    sp.setUrl(downloadAppAddress);
                }
            }
        } else {
            JLog.e("have none match :" + name);
        }
        return sp;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        JLog.e("in item click pos:" + i);
//        if (shares == null) {
//            toast("数据错误");
//            return;
//        }
        ShareItem si = shareAdapter.getItem(i);
        if (si == null || TextUtils.isEmpty(si.getTag())) {
            toast("组件数据错误");
            return;
        }
        String tag = si.getTag();
//        if ("System".equals(tag)) {
//            shareBySystem();
//            pairs = new Pair<>("行为类型", "系统分享");
//            if (onShareAppClickListener != null && pairs != null) {
//                onShareAppClickListener.onClick(pairs);
//            }
//            return;
//        }

        Platform p = ShareSDK.getPlatform(tag);
//        ShareSDK.

        setSharePlatform(p);
        Platform.ShareParams sp = getShareParams(p.getName());
        if (sp == null) {
            toast("解析分享渠道错误");
            return;
        }
        JLog.e("platform:" + p + " listener:" + p.getPlatformActionListener());
        p.share(sp);
        if (onShareAppClickListener != null && pairs != null) {
            onShareAppClickListener.onClick(pairs);
        }
//        dismiss();
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        handler.sendEmptyMessage(WHAT_SUC);
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        Message msg = Message.obtain();
        msg.what = WHAT_ERROR;
        msg.obj = "分享失败";
        if (throwable != null) {
            throwable.printStackTrace();
            JLog.e("msg:" + throwable.getMessage() + "\ncause:" + throwable.getCause()
                    + "\n" + throwable.getLocalizedMessage());
            String expName = throwable.getClass().getSimpleName();
            String strName = null;
            if ("WechatClientNotExistException".equals(expName)
                    || "WechatTimelineNotSupportedException".equals(expName)
                    || "WechatFavoriteNotSupportedException".equals(expName)) {
                strName = "ssdk_wechat_client_inavailable";
            } else if ("GooglePlusClientNotExistException".equals(expName)) {
                strName = "ssdk_google_plus_client_inavailable";
            } else if ("QQClientNotExistException".equals(expName)) {
                strName = "ssdk_qq_client_inavailable";
            } else if ("YixinClientNotExistException".equals(expName)
                    || "YixinTimelineNotSupportedException".equals(expName)) {
                strName = "ssdk_yixin_client_inavailable";
            } else if ("KakaoTalkClientNotExistException".equals(expName)) {
                strName = "ssdk_kakaotalk_client_inavailable";
            } else if ("KakaoStoryClientNotExistException".equals(expName)) {
                strName = "ssdk_kakaostory_client_inavailable";
            } else if ("WhatsAppClientNotExistException".equals(expName)) {
                strName = "ssdk_whatsapp_client_inavailable";
            } else if ("FacebookMessengerClientNotExistException".equals(expName)) {
                strName = "ssdk_facebookmessenger_client_inavailable";
            } else if (throwable.getMessage() != null && throwable.getMessage().contains("invalid_access_token")) {
                strName = "权限错误:" + throwable.getMessage();
            } else {
                strName = "ssdk_oks_share_failed";
            }

            if (strName != null) {
//                int resId = com.mob.tools.utils.R.getStringRes(getContext(), strName);
                int resId = com.mob.tools.utils.ResHelper.getStringRes(getContext(), strName);
                if (resId > 0) {
                    msg.obj = getContext().getString(resId);
                }
            }
//            toast(throwable.getMessage());
        }
        handler.sendMessage(msg);
    }

    @Override
    public void onCancel(Platform platform, int i) {
        JLog.e("ShareFragment ", "------onCancel--------");
        handler.sendEmptyMessage(WHAT_CANCLE);
    }
//
//    public void shareBySystem() {
//        Intent shareIntent = new Intent(Intent.ACTION_SEND);
//        shareIntent.setType("image/*");
//        shareIntent.putExtra(Intent.EXTRA_TEXT, "四川观察APP---点击下载");
////        shareIntent.putExtra(Intent.)
//        startActivity(Intent.createChooser(shareIntent, getString(com.ruihang.generalibrary.R.string.share_system_title)));
//    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg == null) {
                return;
            }
            JLog.e("msg:" + msg);
            switch (msg.what) {
                case WHAT_ERROR:
                    toast((String) msg.obj);
                    break;
                case WHAT_CANCLE:
                    toast("分享取消");
                    break;
                case WHAT_SUC:
                    toast("分享成功");
                    if(null!=shareListener){
                        shareListener.OnShareSuccess();
                    }
                    dismissAllowingStateLoss();
                    break;
            }
        }
    };

    public static boolean isValidClientSina(String akp) {
        PackageInfo pi;
        try {
            pi = MobSDK.getContext().getPackageManager().getPackageInfo(
                    akp, PackageManager.GET_RESOLVED_FILTER);
            return true;
        } catch (Throwable t) {
        }
        return false;
    }

    public interface ShareSuccess{
        void OnShareSuccess();
    }
}
